# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import csv
from pymongo import MongoClient


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告


"""
抖音视频下载地址-通过分享链接
1.通过PC端
2.通过移动端
"""


class VideoDown():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        # requests.utils.dict_from_cookiejar(html.cookies)  # 获取cookies转dict
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        }

    # 从pc端获取视频地址
    def get_video_url_pc(self, shareurl):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36',
        }
        html = HttpUtils.do_request("GET", shareurl, headers, "")
        down_url = re.findall(r"playAddr:(.*?),", html.text)[0].replace("\"", "").strip()
        pass

    # 从mobile端获取视频地址
    def get_video_url_mobile(self, shareurl):
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        }
        html = HttpUtils.do_request("GET", shareurl, headers, "")
        item_ids = re.findall(r"itemId:(.*?),", html.text)[0].replace("\"", "").strip()
        dytk = re.findall(r"dytk:(.*?)}", html.text)[0].replace("\"", "").strip()
        postData = {
            'item_ids': item_ids,
            'dytk': dytk
        }
        video_url = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo"
        html_video = HttpUtils.do_request("GET", video_url, headers, postData)
        data_json = json.loads(html_video.text)
        desc = data_json['item_list'][0]['desc']  # 简介
        tag_name = ""  # title 话题
        for t in data_json['item_list'][0]['text_extra']:
            tag_name += "#" + t['hashtag_name']
        video_url1 = data_json['item_list'][0]['video']['play_addr']['list_url'][0]  # 真实下载地址
        pass


if __name__ == '__main__':
    videodown = VideoDown()

    share_url ="https://www.iesdouyin.com/share/video/6826775885937380621/?region=CN&mid=6826775849979808519&u_code=0&titleType=title"
    # 从pc端获取视频地址
    videodown.get_video_url_pc(share_url)
    # 从mobile端获取视频地址
    videodown.get_video_url_mobile(share_url)

